import 'dart:async';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:tolyui_navigation/tolyui_navigation.dart';
import 'package:window_manager/window_manager.dart';
import 'package:yuellyfactory/util/AuthUtil.dart';
import 'package:yuellyfactory/util/BaseRequest.dart';
import 'package:yuellyfactory/util/ColorUtil.dart';
import 'package:yuellyfactory/util/DialogUtil.dart';
import 'package:yuellyfactory/util/GlobalData.dart';
import 'package:yuellyfactory/util/StorageUtil.dart';

import 'package:yuellyfactory/views/base/BaseVC.dart';
import 'package:yuellyfactory/views/dto/Supplier.dart';
import 'package:yuellyfactory/views/login/LoginVC.dart';
import 'package:yuellyfactory/views/model/ModelVC.dart';
import 'package:yuellyfactory/views/price/PriceVC.dart';
import 'package:yuellyfactory/views/purchase/PurchaseVC.dart';
import 'package:yuellyfactory/views/supplier/SupplierVC.dart';

import '../../util/ViewUtil.dart';
import 'components/MainTopButton.dart';
import 'eventbus/EventBusUtil.dart';
import 'eventbus/EventRefreshSupplier.dart';


class MainPageVC extends StatefulWidget {
  const MainPageVC({super.key});

  @override
  State<MainPageVC> createState() => _MainPageVCState();
}

class _MainPageVCState extends State<MainPageVC> {

  int currentPage=0;
  bool isFullScreen=false;
  StreamSubscription? streamSubscription;

  late MenuTreeMeta _treeMeta;
  var appVersion="";
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getAppVersion();
    List<Map<String, dynamic>> children=[];
    if(AuthUtil.instance.checkMenu(AuthUtil.Menu_Base_Manage)){
      children.add({
        "path":"/base",
        "label":"基础数据"
      });
    }
    if(AuthUtil.instance.checkMenu(AuthUtil.Menu_Model_Manage)){
      children.add({
        "path":"/model",
        "label":"机型配置"
      });
    }
    if(AuthUtil.instance.checkMenu(AuthUtil.Menu_Purchase_Manage)){
      children.add({
        "path":"/purchase",
        "label":"成本核算"
      });
    }
    if(AuthUtil.instance.checkMenu(AuthUtil.Menu_Price_Select)){
      children.add({
        "path":"/price",
        "label":"价格选型"
      });
    }
    if(AuthUtil.instance.checkMenu(AuthUtil.Menu_Supplier_Manage)){
      children.add({
        "path":"/supplier",
        "label":"供应商管理"
      });
    }


    Map<String,dynamic> menuData={
      'path':"",
      "label":"",
      "children":children
    };

    MenuNode root=MenuNode.fromMap(menuData);
    _treeMeta=MenuTreeMeta(expandMenus: ['/base'], activeMenu: root.find('/base'), root: root);


    streamSubscription=eventBus.on<EventRefreshSupplier>().listen((event){

      getAllSupplier();
    });

  }

  @override
  void dispose() {
    if(streamSubscription!=null) {
      streamSubscription!.cancel();
    }

    super.dispose();
  }

  Future<void> getAppVersion() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();



    appVersion = "V"+packageInfo.version; // 版本名称（如 1.0.0）

    setState(() {

    });


  }


  @override
  Widget build(BuildContext context) {
    return
      Scaffold(
        // 主内容区域
        body:
        Container(color: Colors.white,child:

         Column(
           children: [
             if(Platform.isWindows)
            Container(
              color: const Color(0xff383837),
              height: 40,
              alignment: Alignment.centerLeft,
              child: Row(
                children: [
                  const SizedBox(width: 20,),
                  Image.asset('images/logo.png',width: 40,),
                  const SizedBox(width: 20,),
                  const Text("约利系统",style: TextStyle(color: Colors.white,fontSize: 16),),
                  Expanded(child: Container()),

                  Text(appVersion,style: TextStyle(color: Colors.white,fontSize: 16),),

                  IconButton(icon: const Icon(Icons.minimize_outlined),color:Colors.white,
                    iconSize: 20,onPressed: () async {
                      windowManager.minimize();
                    },),
                  IconButton(icon: isFullScreen?const Icon(Icons.fullscreen_exit):const Icon(Icons.fullscreen),color:Colors.white,
                    iconSize: 22,onPressed: () async {
                      if(isFullScreen){
                        isFullScreen=!isFullScreen;
                        windowManager.setFullScreen(false);
                      }else{
                        isFullScreen=!isFullScreen;
                        windowManager.setFullScreen(true);
                      }
                      setState(() {

                      });
                    },),

                  IconButton(icon: const Icon(Icons.close),color:Colors.white,
                    iconSize: 20,onPressed: () async {
                      windowManager.close();
                    },),
                  const SizedBox(width: 5,),
                ],
              ),
            ),
            Expanded(child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(width: 120,
                  color: const Color(0xff383837),
                  padding: EdgeInsets.only(top: ViewUtil.screenHeight(2)),
                  child: Column(
                    children: [

                      SizedBox(height: ViewUtil.screenHeight(1000),
                        child:Align(
                          alignment: Alignment.topLeft,
                          child: TolyRailMenuTree(meta: _treeMeta,
                              enableWidthChange: true,

                              cellStyle: MenuTreeCellStyle(
                                  hoverForegroundColor:  ColorUtil.colorBlue,
                                  activeForegroundColor: const  Color(0xff02589F),
                                  inactiveBackgroundColor: Colors.white,
                                  inactiveForegroundColor: Colors.white,
                                  activeBackgroundColor: Colors.white),

                              onSelect: onSelect),

                        ),
                      ),

                      Expanded(child: Container()),
                      ViewUtil.logoutIcon('退出登录', (){
                        showLogoutDialog();


                      }),
                    ],
                  ),
                ),

                // 可调整大小的左右分栏布局
                Expanded(
                    child: Stack(
                      children: [
                        Visibility(
                            visible: currentPage==0,
                            child: const BaseVC()),
                        Visibility(
                            visible: currentPage==1,
                            child: const ModelVC()),
                        Visibility(
                            visible: currentPage==2,
                            child: const PurchaseVC()),
                        Visibility(
                            visible: currentPage==3,
                            child: const PriceVC()),
                        Visibility(
                            visible: currentPage==4,
                            child: const SupplierVC()),
                      ],
                    )


                ),
              ],
            ))
             ,
           ],
         )

        ),

      );
  }


  void onSelect(MenuNode menu){
    _treeMeta=_treeMeta.select(menu,singleExpand: true);
    if(menu.data.route=='/base'){
      currentPage=0;
    }else if(menu.data.route=='/model'){
      currentPage=1;
    }else if(menu.data.route=='/purchase'){
      currentPage=2;
    }else if(menu.data.route=='/price'){
      currentPage=3;
    }else if(menu.data.route=='/supplier'){
      currentPage=4;
    }
    setState(() {

    });
  }

  void showLogoutDialog(){
    DialogUtil.showConfimDialog(context, '退出登录', "确定退出登录?", "确定", (){

      StorageUtil.saveToken("");
      Get.off(const LoginVC());

    });
  }


  getAllSupplier(){
    BaseRequest.postHttp('supplier/list', parameters: {"pageSize":"10000","page":'1'},
        canTip: true,
        context: context,
        onSuccess: (data) {
          bool result = BaseRequest.chekResponse(data, true);
          if (result) {
            dynamic records = data["data"]["records"];
            Map<String,Supplier> allModel = {};
            for (var i = 0; i < records.length; i++) {
              var item = records[i];
              var part = Supplier.fromJson(item);
              allModel[part.id]=part;
            }
            GlobalData.allSupplier=allModel;

          }
        },
        onError: (error) {

        });

  }
}

